/**
 * 文档列表页
 * Phase 1: 前端 MVP 使用
 * 
 * 功能：
 * - 文档列表展示
 * - 搜索和筛选
 * - 分页
 * - 分类筛选
 * - 状态筛选
 */

import React, { useState, useMemo } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Container } from '@/components/ui/container';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import {
  ResponsiveTable,
  ResponsiveTableHeader,
  ResponsiveTableRow,
  ResponsiveTableHead,
  ResponsiveTableCell,
  TableLoading,
  TableEmpty
} from '@/components/ui/responsive-table';
import { TableBody } from '@/components/ui/table';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Search, 
  Plus, 
  FileText, 
  Eye, 
  Calendar,
  User,
  Filter,
  RefreshCw,
  HardDrive
} from 'lucide-react';
import { documentService, categoryService } from '@/lib/api/services/documentation-service';
import { cn } from '@/lib/utils';

const DocListPage = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  
  // 状态
  const [searchKeyword, setSearchKeyword] = useState(searchParams.get('q') || '');
  const [categoryFilter, setCategoryFilter] = useState(searchParams.get('category') || '');
  const [statusFilter, setStatusFilter] = useState(searchParams.get('status') || '');
  const [page, setPage] = useState(parseInt(searchParams.get('page') || '1'));
  const [pageSize] = useState(10);

  // 获取文档列表
  const { 
    data: documentsData, 
    isLoading, 
    error, 
    refetch 
  } = useQuery({
    queryKey: ['documents', 'list', searchKeyword, categoryFilter, statusFilter, page, pageSize],
    queryFn: () => documentService.getList({
      keyword: searchKeyword,
      categoryId: categoryFilter,
      status: statusFilter,
      page,
      pageSize
    })
  });

  // 获取分类列表
  const { data: categoriesData } = useQuery({
    queryKey: ['documents', 'categories'],
    queryFn: () => categoryService.getAll()
  });

  // 搜索处理
  const handleSearch = (value) => {
    setSearchKeyword(value);
    setPage(1);
    updateURL({ q: value, page: 1 });
  };

  // 分类筛选
  const handleCategoryChange = (value) => {
    const category = value === 'all' ? '' : value;
    setCategoryFilter(category);
    setPage(1);
    updateURL({ category, page: 1 });
  };

  // 状态筛选
  const handleStatusChange = (value) => {
    const status = value === 'all' ? '' : value;
    setStatusFilter(status);
    setPage(1);
    updateURL({ status, page: 1 });
  };

  // 更新 URL 参数
  const updateURL = (params) => {
    const newParams = new URLSearchParams(searchParams);
    Object.entries(params).forEach(([key, value]) => {
      if (value) {
        newParams.set(key, value);
      } else {
        newParams.delete(key);
      }
    });
    setSearchParams(newParams);
  };

  // 分页处理
  const handlePageChange = (newPage) => {
    setPage(newPage);
    updateURL({ page: newPage });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // 格式化日期
  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  };

  // 获取所有分类（扁平化）
  // Mock 和 API Service 层返回格式一致：直接是数组
  const allCategories = useMemo(() => {
    if (!categoriesData || !Array.isArray(categoriesData)) {
      return [];
    }
    
    const flatten = [];
    categoriesData.forEach(cat => {
      flatten.push({ id: cat.id, name: cat.name });
      if (cat.children) {
        cat.children.forEach(child => {
          flatten.push({ id: child.id, name: `${cat.name} / ${child.name}` });
        });
      }
    });
    return flatten;
  }, [categoriesData]);

  // 处理文档列表数据
  // Mock 和 API Service 层返回格式一致：PageResponse { data, page, pageSize, total, totalPages, hasNext, hasPrevious }
  const documents = documentsData?.data || [];
  const meta = {
    page: documentsData?.page || 1,
    pageSize: documentsData?.pageSize || 10,
    total: documentsData?.total || 0,
    totalPages: documentsData?.totalPages || 0
  };

  return (
    <Container>
      {/* 页面标题 */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold">技术文档</h1>
          <p className="text-muted-foreground mt-1">
            共 {meta.total} 篇文档
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Link to="/documentation/files">
            <Button variant="outline">
              <HardDrive className="size-4 mr-2" />
              MinIO 文件
            </Button>
          </Link>
          <Link to="/documentation/new">
            <Button>
              <Plus className="size-4 mr-2" />
              新建文档
            </Button>
          </Link>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>文档列表</CardTitle>
        </CardHeader>
        <CardContent>
          {/* 搜索和筛选 */}
          <div className="flex flex-col md:flex-row gap-4 mb-6">
            {/* 搜索框 */}
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-gray-400" />
              <Input
                placeholder="搜索文档标题、内容..."
                value={searchKeyword}
                onChange={(e) => handleSearch(e.target.value)}
                className="pl-10"
              />
            </div>

            {/* 分类筛选 */}
            <Select 
              value={categoryFilter || 'all'} 
              onValueChange={handleCategoryChange}
            >
              <SelectTrigger className="w-full md:w-48">
                <Filter className="size-4 mr-2" />
                <SelectValue placeholder="全部分类" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部分类</SelectItem>
                {allCategories.map(cat => (
                  <SelectItem key={cat.id} value={String(cat.id)}>
                    {cat.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            {/* 状态筛选 */}
            <Select 
              value={statusFilter || 'all'} 
              onValueChange={handleStatusChange}
            >
              <SelectTrigger className="w-full md:w-36">
                <SelectValue placeholder="全部状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="published">已发布</SelectItem>
                <SelectItem value="draft">草稿</SelectItem>
              </SelectContent>
            </Select>

            {/* 刷新按钮 */}
            <Button 
              variant="outline" 
              size="icon"
              onClick={() => refetch()}
              title="刷新"
            >
              <RefreshCw className="size-4" />
            </Button>
          </div>

          {/* 表格 */}
          <ResponsiveTable>
            <ResponsiveTableHeader>
              <ResponsiveTableRow>
                <ResponsiveTableHead>标题</ResponsiveTableHead>
                <ResponsiveTableHead hideOnMobile>分类</ResponsiveTableHead>
                <ResponsiveTableHead hideOnMobile>作者</ResponsiveTableHead>
                <ResponsiveTableHead hideOnTablet>浏览量</ResponsiveTableHead>
                <ResponsiveTableHead hideOnMobile>更新时间</ResponsiveTableHead>
                <ResponsiveTableHead>状态</ResponsiveTableHead>
                <ResponsiveTableHead>操作</ResponsiveTableHead>
              </ResponsiveTableRow>
            </ResponsiveTableHeader>

            <TableBody>
              {isLoading ? (
                // 加载骨架屏
                Array.from({ length: 5 }).map((_, i) => (
                  <ResponsiveTableRow key={i}>
                    <ResponsiveTableCell>
                      <Skeleton className="h-4 w-48" />
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnMobile>
                      <Skeleton className="h-4 w-24" />
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnMobile>
                      <Skeleton className="h-4 w-16" />
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnTablet>
                      <Skeleton className="h-4 w-12" />
                    </ResponsiveTableCell>
                    <ResponsiveTableCell hideOnMobile>
                      <Skeleton className="h-4 w-20" />
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <Skeleton className="h-6 w-16" />
                    </ResponsiveTableCell>
                    <ResponsiveTableCell>
                      <Skeleton className="h-8 w-16" />
                    </ResponsiveTableCell>
                  </ResponsiveTableRow>
                ))
              ) : error ? (
                // 错误状态
                <ResponsiveTableRow>
                  <ResponsiveTableCell colSpan={7} className="text-center py-8">
                    <div className="flex flex-col items-center gap-4">
                      <p className="text-destructive">加载失败: {error.message}</p>
                      <Button 
                        variant="outline" 
                        onClick={() => refetch()}
                      >
                        重试
                      </Button>
                    </div>
                  </ResponsiveTableCell>
                </ResponsiveTableRow>
              ) : documents.length === 0 ? (
                // 空状态
                <ResponsiveTableRow>
                  <ResponsiveTableCell colSpan={7} className="text-center py-12">
                    <FileText className="size-12 mx-auto mb-4 text-gray-400" />
                    <p className="text-gray-500 mb-4">
                      {searchKeyword || categoryFilter || statusFilter 
                        ? '未找到匹配的文档' 
                        : '暂无文档，点击上方按钮开始创建'}
                    </p>
                    {(searchKeyword || categoryFilter || statusFilter) && (
                      <Button 
                        variant="outline"
                        onClick={() => {
                          setSearchKeyword('');
                          setCategoryFilter('');
                          setStatusFilter('');
                          setSearchParams({});
                        }}
                      >
                        清除筛选
                      </Button>
                    )}
                  </ResponsiveTableCell>
                </ResponsiveTableRow>
              ) : (
                // 文档列表
                documents.map((doc) => (
                  <ResponsiveTableRow key={doc.id}>
                    {/* 标题 */}
                    <ResponsiveTableCell className="font-medium">
                      <Link 
                        to={`/documentation/${doc.slug}`}
                        className="hover:text-primary transition-colors flex items-center gap-2"
                      >
                        <FileText className="size-4 flex-shrink-0" />
                        <span className="line-clamp-1">{doc.title}</span>
                      </Link>
                      {doc.summary && (
                        <p className="text-xs text-muted-foreground mt-1 line-clamp-2 md:hidden">
                          {doc.summary}
                        </p>
                      )}
                    </ResponsiveTableCell>

                    {/* 分类 */}
                    <ResponsiveTableCell hideOnMobile>
                      <Badge variant="outline" className="text-xs">
                        {doc.categoryName}
                      </Badge>
                    </ResponsiveTableCell>

                    {/* 作者 */}
                    <ResponsiveTableCell hideOnMobile>
                      <div className="flex items-center gap-2">
                        <User className="size-3 text-gray-400" />
                        <span className="text-sm">{doc.author}</span>
                      </div>
                    </ResponsiveTableCell>

                    {/* 浏览量 */}
                    <ResponsiveTableCell hideOnTablet>
                      <div className="flex items-center gap-2 text-sm text-gray-600">
                        <Eye className="size-3" />
                        {doc.viewCount}
                      </div>
                    </ResponsiveTableCell>

                    {/* 更新时间 */}
                    <ResponsiveTableCell hideOnMobile>
                      <div className="flex items-center gap-2 text-sm text-gray-600">
                        <Calendar className="size-3" />
                        {formatDate(doc.updatedAt)}
                      </div>
                    </ResponsiveTableCell>

                    {/* 状态 */}
                    <ResponsiveTableCell>
                      <Badge 
                        variant={doc.status === 'published' ? 'default' : 'secondary'}
                        className="text-xs"
                      >
                        {doc.status === 'published' ? '已发布' : '草稿'}
                      </Badge>
                    </ResponsiveTableCell>

                    {/* 操作 */}
                    <ResponsiveTableCell>
                      <div className="flex items-center gap-2">
                        <Link to={`/documentation/${doc.slug}`}>
                          <Button variant="ghost" size="sm">
                            查看
                          </Button>
                        </Link>
                        <Link to={`/documentation/edit/${doc.id}`}>
                          <Button variant="ghost" size="sm">
                            编辑
                          </Button>
                        </Link>
                      </div>
                    </ResponsiveTableCell>
                  </ResponsiveTableRow>
                ))
              )}
            </TableBody>
          </ResponsiveTable>

          {/* 分页 */}
          {meta.totalPages > 1 && (
            <div className="flex items-center justify-between mt-6">
              <div className="text-sm text-gray-600">
                显示第 {(meta.page - 1) * meta.pageSize + 1} - {Math.min(meta.page * meta.pageSize, meta.total)} 条，共 {meta.total} 条
              </div>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handlePageChange(meta.page - 1)}
                  disabled={meta.page === 1}
                >
                  上一页
                </Button>
                <div className="flex items-center gap-1">
                  {Array.from({ length: Math.min(meta.totalPages, 5) }, (_, i) => {
                    const pageNum = meta.page <= 3 
                      ? i + 1
                      : meta.page + i - 2;
                    
                    if (pageNum < 1 || pageNum > meta.totalPages) return null;
                    
                    return (
                      <Button
                        key={pageNum}
                        variant={pageNum === meta.page ? 'default' : 'outline'}
                        size="sm"
                        onClick={() => handlePageChange(pageNum)}
                        className="w-9"
                      >
                        {pageNum}
                      </Button>
                    );
                  })}
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handlePageChange(meta.page + 1)}
                  disabled={meta.page === meta.totalPages}
                >
                  下一页
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </Container>
  );
};

export default DocListPage;

